﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using GlobalOfficeTools.Interfaces.Model;
using GlobalOfficeTools.Framework.CacheService;
using GlobalOfficeTools.MVC3.Models;
using GlobalOfficeTools.MVC3.DomainServices.GeneralSystem;

namespace GlobalOfficeTools.Models
{
    [Export(typeof(ISystemModel))]
    public class SystemModel : ISystemModel
    {
        #region Private Fields 
        public SystemDomainContext _context;
        public ICacheService _cacheService;
        #endregion

        #region Constructor 
        [ImportingConstructor]
        public SystemModel([Import(typeof(ICacheService))] ICacheService cacheService) 
        {
            _context = new SystemDomainContext();
            _cacheService = cacheService;
        }
        #endregion

        #region ISystemModel Implementation 
        public void ListMenus(Action<IEnumerable<SYStblMenu>> callBack)
        {
            if (_cacheService.GetFromCache(_context.ListMenusQuery().ToString()) == null)
            {
                _context.Load(_context.ListMenusQuery(), loadOp =>
                {
                    _cacheService.AddCache(_context.ListMenusQuery().ToString(), loadOp.Entities);
                    callBack(loadOp.Entities);
                }, null);
            }
            else
                callBack(_cacheService.GetFromCache(_context.ListMenusQuery().ToString()) as IEnumerable<SYStblMenu>);
        }
        public void GetMenu(string menuName, Action<SYStblMenu> callBack)
        {
            IEnumerable<SYStblMenu> lstMenu = _cacheService.GetFromCache(_context.ListMenusQuery().ToString()) as IEnumerable<SYStblMenu>;
            var oRET = (from x in lstMenu
                        where x.Name == menuName
                        select x).FirstOrDefault();
            callBack(oRET);
        }

        //public void ListUserStates(Action<IEnumerable<SYSvwUserState>> callBack) 
        //{
        //    if (_cacheService.GetFromCache(_context.ListUserStatesQuery().ToString()) == null)
        //    {
        //        _context.Load(_context.ListUserStatesQuery(), loadOp =>
        //        {
        //            _cacheService.AddCache(_context.ListUserStatesQuery().ToString(), loadOp.Entities);
        //            callBack(loadOp.Entities);
        //        }, null);
        //    }
        //    else
        //        callBack(_cacheService.GetFromCache(_context.ListUserStatesQuery().ToString()) as IEnumerable<SYSvwUserState>);
        //}
        #endregion
    }
}
